package com.ckm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ckm.entity.College;
import com.ckm.entity.Course;
import com.ckm.entity.TeacherCourse;
import com.ckm.exception.BusinessException;
import com.ckm.mapper.CourseMapper;
import com.ckm.mapper.TeacherCourseMapper;
import com.ckm.service.CourseService;
import com.ckm.util.FindObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private TeacherCourseMapper teacherCourseMapper;

    @Override
    public void addCourse(List<Course> courseList) {
        if (courseList == null || courseList.isEmpty()) {
            throw new BusinessException(250,"添加数据集为空");
        }
        for (Course course : courseList) {
            if (!findCourse(course).isEmpty()) {
                throw new BusinessException(250,"数据重复:"+course);
            }
            courseMapper.insert(course);
        }
        log.info("添加数据：{}", courseList);
    }

    @Override
    public void deleteCourse(Integer id) {
        if (id==null){
            throw new BusinessException(250,"删除参数为空");
        }
        if (courseMapper.selectById(id)==null){
            throw new BusinessException(250,"无此课程");
        }
        courseMapper.deleteById(id);
    }

    @Override
    public void updateCourse(Course course) {
        if (course.getId()==null){
            throw new BusinessException(250,"更新信息缺少id");
        }
        Course select = courseMapper.selectById(course.getId());
        if (select==null){
            throw new BusinessException(250,"无此课程");
        }
        if (select.equals(course)){
            throw new BusinessException(250,"信息无更改");
        }
        courseMapper.updateById(course);
    }

    @Override
    public PageInfo<Course> getCoursePage(Course course, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(findCourse(course));
    }

    @Override
    public List<Course> findCourse(Course course) {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        FindObjectUtil.fullQueryWrapper(course,wrapper);
        return courseMapper.selectList(wrapper);
    }

    @Override
    public List<Course> findCourseByClassId(Integer classId) {
        List<TeacherCourse> teacherCourseList = teacherCourseMapper.selectList(new QueryWrapper<TeacherCourse>().eq("class_id", classId));
        return courseMapper.selectBatchIds(teacherCourseList.stream().map(TeacherCourse::getCourseId).toList());
    }
}
